package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import javafx.beans.binding.ObjectExpression;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 发送验证码
     * @return
     */
    @PostMapping("/sendMsg")

    public Result sendMsg(@RequestBody User user, HttpServletRequest request) {
        //获取用户的号码
        String phone = user.getPhone();

        //判断手机号是否为空,如果不为空就生成验证码,并且给用户发送验证码,把验证码存储在session中
        if (StringUtils.isNotEmpty(phone)) {

            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            log.info("code:{}", code);

            //调用阿里云提供的短信服务API发送短信
            //SMSUtils.sendMessage("瑞吉外面", phone, code);

            //将生成的验证码保存到session中
            //request.getSession().setAttribute(phone, code);

            //将生成的验证码缓存到Redis中
            redisTemplate.opsForValue().set(phone, code.toString(), 5, TimeUnit.MINUTES);


            return Result.success("发送成功");

        }

        return Result.error("发送失败");
    }

    /**
     * 登录操作
     * @param map
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map map, HttpServletRequest request) {
        //接收用户的号码和 验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //从session中获取保存的验证码
        //String result =  request.getSession().getAttribute(phone).toString();
        //从Redis中获取验证码
        Object result = redisTemplate.opsForValue().get(phone);

        //进行验证码的比对
        if (result != null && result.equals(code)) {
            //如果能比对成功,则说明登录成功,然后判断该用户是否是第一次登录,如果是第一次登录,则将该用户的信息存储到数据库中
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);

            User user = userService.getOne(wrapper);

            if (user == null) {
                 user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }

            System.out.println(user.getId());
            request.getSession().setAttribute("user", user.getId());

            //删除Redis中缓存的验证码
            redisTemplate.delete(phone);
            return Result.success();

        }
        return Result.error("登录失败");

    }


    @PostMapping("/loginout")
    public Result loginout(HttpServletRequest request) {

        request.getSession().invalidate();

        return Result.success();
    }


}
